﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using Infragistics.WebUI.UltraWebGrid;

public partial class Custom_BwCheckItemMaintForm : BaseForm
{
    int m_PageSize = 30;
    uMESContainerBusiness containerBal = new uMESContainerBusiness();//test 0922
    uMESCheckItemInfoBusiness checkItemBal = new uMESCheckItemInfoBusiness();

    FreeTextBoxControls.FreeTextBox oHtml = new FreeTextBoxControls.FreeTextBox();

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：检测项维护";
        master.strTitle = "检测项维护";
        master.ChangeFrame(true);

        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { SearchData(upageTurning.CurrentPageIndex); });
        getProductInfo.GetProductData += new GetProductInfo_ascx.GetProductDataEventHandler(LoadProductData);
        getWorkFlowInfo.GetWorkFlowData += new GetWorkFlowInfo_ascx.GetWorkFlowDataEventHandler(LoadWorkflowData);
        getProductInfo.DDlProductDataChanged += new GetProductInfo_ascx.DDlProductDataChangedEventHandler(DDlProductDataChanged);
        getWorkFlowInfo.DDlWorkFlowDataChanged += new GetWorkFlowInfo_ascx.DDlWorkFlowDataChangedEventHandler(DDlWorkflowDataChanged);
        oHtml = wucToleranceInput1.FindControl("ftbFinalHtml") as FreeTextBoxControls.FreeTextBox;

        if (IsPostBack == false)
        {
            //return ((confirm('确认删除？') == true) ? true : false)
            btnDel.Attributes.Add("onclick", "javascript:return confirm('确认删除?')");//
            InitControl();
            ShowStatusMessage("", true);
            //ClearMessage();
        }
    }



    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");";
        //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        //ClientScript.RegisterStartupScript(this.GetType(), "", strScript);
        ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "Message", strScript, true);

    }

    /// <summary>
    /// 清除提示信息
    /// </summary>
    protected void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"\", true);</script>";
        LiteralControl child = new LiteralControl(strScript);
        //WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    #region 事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //ClearMessage();
        ShowStatusMessage("", true);
        try { ClearData(false, true, true); SearchData(1); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ///Response.Redirect(Request.Url.AbsoluteUri);
        ClearData(true, true, true);
    }
    protected void gdContainer_ActiveRowChange(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        //ClearMessage();
        ShowStatusMessage("", true);
        ClearData(false, false, true);
        activeRow(e.Row);
        System.Threading.Thread.Sleep(400);

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        ClearData(false, true, true);
        ShowStatusMessage("", true);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //ClearMessage();


        try
        {
            ResultModel re = SaveData();
            if (re.IsSuccess)
            {
                ClearData(false, true, true);
                SearchData(1);
            }
            ShowStatusMessage(re.Message, re.IsSuccess);
            ShowStatusMessage("", true);
        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        //ClearMessage();
        //string strScript = "return ((confirm('确认删除？') == true) ? true :  false); ";
        //ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "Message", strScript, true);
        try
        {
            ResultModel re = DeleteData();
            if (re.IsSuccess)
            {
                SearchData(1);
                ClearData(false, false, true);
            }
            ShowStatusMessage(re.Message, re.IsSuccess);
            ShowStatusMessage("", true);
        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }
    #endregion

    #region 方法

    void SearchData(int index)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();

        para["ProductId"] = getProductInfo.ProductValue;
        para["WorkflowId"] = getWorkFlowInfo.WorkFlowValue;
        para["SpecId"] = ddlStep.SelectedValue;

        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();

        uMESPagingDataDTO result = checkItemBal.GetCheckItemInfo(para);

        DataTable dt = result.DBTable;
        dt.Columns.Add("CheckitemDis");

        DataTable dd = new DataTable();
        foreach (DataRow dr in dt.Rows)
        {
            string codeDis = "";
            wucToleranceInput1.ParseCode(dr["CheckItem"].ToString(), ref dd, ref codeDis);
            dr["CheckitemDis"] = codeDis;

            if (dr["keyspec"].ToString() == "1")
                dr["keyspec"] = "是";
            else
                dr["keyspec"] = "否";

            if (dr["firstcheck"].ToString() == "1")
                dr["firstcheck"] = "是";
            else
                dr["firstcheck"] = "否";

            if (dr["speccheck"].ToString() == "1")
                dr["speccheck"] = "是";
            else
                dr["speccheck"] = "否";

            if (dr["factoryrecheck"].ToString() == "1")
                dr["factoryrecheck"] = "是";
            else
                dr["factoryrecheck"] = "否";


        }


        this.gdContainer.DataSource = result.DBTable;
        this.gdContainer.DataBind();

        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }

    /// <summary>
    /// 清除数据
    /// </summary>
    /// <param name="isCondition"></param>
    /// <param name="isGrid"></param>
    /// <param name="isDetail"></param>
    void ClearData(bool isCondition, bool isGrid, bool isDetail)
    {
        if (isCondition)
        {
            getProductInfo.InitControl();
            getWorkFlowInfo.InitControl();
            ddlStep.Items.Clear();
        }
        if (isGrid)
        {
            gdContainer.Rows.Clear();
        }
        if (isDetail)
        {
            FreeTextBoxControls.FreeTextBox oHtmlDisp = wucToleranceInput1.FindControl("ftbFinalHtml") as FreeTextBoxControls.FreeTextBox;
            oHtmlDisp.Text = "";

            txtCheckName.Text = "";
            ckFirstCheck.Checked = false;
            ckKeySpec.Checked = false;
            ckSpecCheck.Checked = false;
            ckFactoryReCheck.Checked = false;
        }
    }

    void LoadProductData()
    {
        ddlStep.Items.Clear();
        if (getProductInfo.Message.Length > 0)
        {
            ShowStatusMessage(getProductInfo.Message, false);
        }
    }

    void LoadWorkflowData()
    {
        ddlStep.Items.Clear();
        if (getWorkFlowInfo.Message.Length > 0)
        {
            ShowStatusMessage(getWorkFlowInfo.Message, false);
        }
    }
    //获取产品名及版本
    void GetProductInfo(ref string productName, ref string productRev)
    {
        string productInfo = getProductInfo.ProducText;

        productName = productInfo.Substring(0, productInfo.IndexOf(":"));
        productRev = productInfo.Substring(productInfo.IndexOf(":") + 1, productInfo.IndexOf("(", productName.Length) - productInfo.IndexOf(":") - 1);

    }

    //获取工艺名及版本
    void GetWorkflowInfo(ref string workflowName, ref string workflowRev)
    {
        string strWrokflow = getWorkFlowInfo.WorkFlowText;

        workflowName = getWorkFlowInfo.WorkFlowText.Substring(0, strWrokflow.IndexOf(":"));

        workflowRev = strWrokflow.Replace(strWrokflow, "");

    }
    /// <summary>
    /// 件号更改带出工艺
    /// </summary>
    void DDlProductDataChanged()
    {
        ddlStep.Items.Clear();
        getWorkFlowInfo.InitControl();

        string productName = "";

        string productRev = "";

        GetProductInfo(ref productName, ref productRev);

        if (productName == "")
        {
            return;
        }

        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ProductName"] = productName;
        para["ProductRev"] = productRev;

        getWorkFlowInfo.SearchWorkFlow(para, 1);

    }
    /// <summary>
    /// 工艺更改
    /// </summary>
    void DDlWorkflowDataChanged()
    {
        ddlStep.Items.Clear();

        DataTable dt = containerBal.GetStepInfoByWorkflowId(getWorkFlowInfo.WorkFlowValue);

        ddlStep.DataSource = dt;
        ddlStep.DataBind();

    }
    /// <summary>
    /// 初始化控件
    /// </summary>
    void InitControl()
    {
        ddlStep.DataTextField = "SpecName";
        ddlStep.DataValueField = "SpecId";
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns></returns>
    ResultModel SaveData()
    {
        ResultModel re = new ResultModel(false, "");

        if (string.IsNullOrWhiteSpace(getProductInfo.ProductValue) || string.IsNullOrWhiteSpace(getWorkFlowInfo.WorkFlowValue) || string.IsNullOrWhiteSpace(ddlStep.SelectedValue))
        {
            re.Message = "件号或工艺或工序必须选择";
            return re;
        }
        if (string.IsNullOrWhiteSpace(txtCheckName.Text))
        {
            re.Message = "检测项名称必填";
            return re;
        }
        if (ckFirstCheck.Checked == false && ckKeySpec.Checked == false && ckSpecCheck.Checked == false && ckFactoryReCheck.Checked==false)
        {
            re.Message = "关键工序或首件检验或工序检验或入厂检验必须勾选一项";
            return re;
        }
        if (string.IsNullOrWhiteSpace(txtCheckName.Text))
        {
            re.Message = "检测项名称必填";
            return re;
        }
        if (string.IsNullOrWhiteSpace(oHtml.Text.Trim()))
        {
            re.Message = "检测项内容必填";
            return re;
        }

        var strCode = wucToleranceInput1.GetCode();

        UltraGridRow activeRow = gdContainer.DisplayLayout.ActiveRow;

        Dictionary<string, string> para = new Dictionary<string, string>();

        if (activeRow == null)
        {
            para["SaveType"] = "1";//插入
            para["CheckIteminfoId"] = Guid.NewGuid().ToString();
        }
        else
        {
            para["SaveType"] = "2";//更新
            para["CheckIteminfoId"] = activeRow.Cells.FromKey("CheckIteminfoId").Text;
        }
        para["CheckIteminfoName"] = txtCheckName.Text;
        para["SpecId"] = ddlStep.SelectedValue;
        para["ProductId"] = getProductInfo.ProductValue;
        para["CheckItem"] = strCode;

        if (ckKeySpec.Checked)
            para["KeySpec"] = "1";
        else
            para["KeySpec"] = "0";
        if (ckFirstCheck.Checked)
            para["FirstCheck"] = "1";
        else
            para["FirstCheck"] = "0";
        if (ckSpecCheck.Checked)
            para["SpecCheck"] = "1";
        else
            para["SpecCheck"] = "0";

        if (ckFactoryReCheck.Checked)
            para["FactoryReCheck"] = "1";
        else
            para["FactoryReCheck"] = "0";


        para["Notes"] = "";
        para["WorkflowId"] = getWorkFlowInfo.WorkFlowValue;

        re = checkItemBal.SaveCheckItemInfo(para);

        if (re.IsSuccess)
            re.Message = "保存成功";


        return re;
    }

    /// <summary>
    /// 点击行
    /// </summary>
    /// <param name="row"></param>
    void activeRow(UltraGridRow row)
    {
        txtCheckName.Text = row.Cells.FromKey("CheckItemInfoName").Text;

        if (row.Cells.FromKey("FirstCheck").Text == "是")
            ckFirstCheck.Checked = true;
        if (row.Cells.FromKey("KeySpec").Text == "是")
            ckKeySpec.Checked = true;
        if (row.Cells.FromKey("SpecCheck").Text == "是")
            ckSpecCheck.Checked = true;
        if (row.Cells.FromKey("factoryrecheck").Text == "是")
            ckFactoryReCheck.Checked = true;



        oHtml.Text = row.Cells.FromKey("CheckitemDis").Text;

    }

    /// <summary>
    /// 删除数据
    /// </summary>
    /// <returns></returns>
    ResultModel DeleteData()
    {
        ResultModel re = new ResultModel(false, "");
        UltraGridRow activeRow = gdContainer.DisplayLayout.ActiveRow;
        if (activeRow == null)
        {
            re.Message = "请选择记录";
            return re;
        }

        re.IsSuccess = checkItemBal.DeleteCheckItemInfo(activeRow.Cells.FromKey("CheckIteminfoId").Text);

        if (re.IsSuccess)
            re.Message = "删除成功";

        return re;
    }
    #endregion








    protected void Button1_Click(object sender, EventArgs e)
    {

    }
}